package com.hgy.fxui.controller;

import com.hgy.fxui.model.Drug;
import com.hgy.fxui.dao.DrugDao;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

@Slf4j
@Controller
public class DrugManagementController {

    @Setter
    private DrugDao drugDao;

    // 必需的无参构造方法
    public DrugManagementController() {
        log.debug("DrugManagementController实例已创建");
    }

    @FXML
    private TextField searchField;
    @FXML
    private TableView<Drug> drugTable;
    @FXML
    private TableColumn<Drug, Integer> idColumn;
    @FXML
    private TableColumn<Drug, String> nameColumn;
    @FXML
    private TableColumn<Drug, String> specificationColumn;
    @FXML
    private TableColumn<Drug, String> manufacturerColumn;
    @FXML
    private TableColumn<Drug, Double> priceColumn;
    @FXML
    private TableColumn<Drug, Integer> stockColumn;
    @FXML
    private TableColumn<Drug, Void> actionColumn;
    @FXML
    private TableColumn<Drug, LocalDate> createTimeColumn;

    @FXML
    private VBox editForm;
    @FXML
    private TextField nameField;
    @FXML
    private TextField specificationField;
    @FXML
    private TextField manufacturerField;
    @FXML
    private TextField priceField;
    @FXML
    private TextField stockField;

    private final ObservableList<Drug> drugList = FXCollections.observableArrayList();
    private Drug currentDrug; // 用于存储当前正在编辑的药品

    private boolean isUISetupCompleted = false;

    /**
     * FXML自动调用的初始化方法（只做基础UI设置）
     */
    @FXML
    public void initialize() {
        log.info("FXML初始化开始...");

        // 确保只执行一次基础UI设置
        if (!isUISetupCompleted) {
            basicUIInitialize();
            isUISetupCompleted = true;
        }

        log.info("FXML初始化完成...");
    }

    /**
     * 完整的初始化方法
     */
    public void fullInitialize() {
        log.info("开始完整初始化...");

        // 1. 验证依赖
        if (drugDao == null) {
            throw new IllegalStateException("drugDao未初始化!");
        }

        // 2. 确保基础UI设置已完成
        if (!isUISetupCompleted) {
            log.warn("基础UI尚未设置，正在执行...");
            basicUIInitialize();
            isUISetupCompleted = true;
        }

        drugTable.setSelectionModel(null); // 禁用默认选择模型,因为选中了样式会变，不知道怎么取消 TODO

        // 3. 加载数据
        loadDrugData();

        log.info("完整初始化完成...");
    }

    /**
     * 基本UI初始化
     */
    private void basicUIInitialize() {
        log.debug("执行基础UI初始化...");

        // 初始化表格列
        idColumn.setCellValueFactory(new PropertyValueFactory<>("id"));
        nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
        specificationColumn.setCellValueFactory(new PropertyValueFactory<>("specification"));
        manufacturerColumn.setCellValueFactory(new PropertyValueFactory<>("manufacturer"));
        priceColumn.setCellValueFactory(new PropertyValueFactory<>("price"));
        stockColumn.setCellValueFactory(new PropertyValueFactory<>("stock"));
        createTimeColumn.setCellValueFactory(new PropertyValueFactory<>("createTime"));

        // 初始化操作列
        setupActionColumn();

        // 设置表格数据源
        drugTable.setItems(drugList);

        // 默认隐藏编辑表单
        editForm.setVisible(false);

        log.debug("基础UI初始化完成");
    }

    /**
     * 加载药品数据
     */
    public void loadDrugData() {
        if (drugDao == null) {
            log.error("尝试加载数据时drugDao为null!");
            throw new IllegalStateException("drugDao未初始化!");
        }

        try {
            log.info("开始从数据库加载药品数据...");
            List<Drug> drugs = drugDao.getAllDrugs();

            if (drugs == null) {
                log.warn("drugDao.getAllDrugs()返回null");
            } else {
                log.info("成功加载 {} 条药品数据", drugs.size());
                drugList.setAll(drugs);
            }
        } catch (Exception e) {
            log.error("加载药品数据失败", e);
            showAlert("无法加载药品数据: " + e.getMessage());
        }
    }

    /**
     * 刷新药品数据（供外部调用）
     */
    public void refreshData() {
        log.info("刷新药品数据...");
        loadDrugData();
    }

    /**
     * 设置操作列的单元格工厂
     */
    private void setupActionColumn() {
        actionColumn.setCellFactory(param -> new TableCell<>() {
            private final Button editButton = new Button("编辑");
            private final Button deleteButton = new Button("删除");
            private final HBox pane = new HBox(editButton, deleteButton);

            {
                pane.setSpacing(10);
                editButton.getStyleClass().add("btn-edit");
                deleteButton.getStyleClass().add("btn-delete");

                editButton.setOnAction(event -> {
                    Drug drug = getTableView().getItems().get(getIndex());
                    handleEdit(drug);
                });
                deleteButton.setOnAction(event -> {
                    Drug drug = getTableView().getItems().get(getIndex());
                    handleDelete(drug);
                });
            }

            @Override
            protected void updateItem(Void item, boolean empty) {
                super.updateItem(item, empty);
                if (empty) {
                    setGraphic(null);
                } else {
                    setGraphic(pane);
                }
            }
        });
    }

    /**
     * 处理搜索功能
     */
    @FXML
    private void handleSearch() {
        String keyword = searchField.getText().trim().toLowerCase();
        if (keyword.isEmpty()) {
            drugTable.setItems(drugList);
            log.info("搜索已清除");
        } else {
            ObservableList<Drug> filteredList = drugList.filtered(drug ->
                    drug.getName().toLowerCase().contains(keyword) ||
                            drug.getManufacturer().toLowerCase().contains(keyword)
            );
            drugTable.setItems(filteredList);
            log.info("实时搜索: {} - 找到 {} 条结果", keyword, filteredList.size());
        }
    }

    /**
     * 处理新增药品
     */
    @FXML
    private void handleAdd() {
        log.info("用户点击添加新药品");
        currentDrug = null; // 表示新增
        clearFormFields();
        editForm.setVisible(true);
    }

    /**
     * 处理编辑药品
     */
    private void handleEdit(Drug drug) {
        log.info("编辑药品: ID={}, 名称={}", drug.getId(), drug.getName());
        currentDrug = drug;
        populateFormFields(drug);
        editForm.setVisible(true);
    }

    /**
     * 处理删除药品
     */
    private void handleDelete(Drug drug) {
        log.info("尝试删除药品: ID={}, 名称={}", drug.getId(), drug.getName());

        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setTitle("确认删除");
        alert.setHeaderText(null);
        alert.setContentText("确定要删除药品【" + drug.getName() + "】吗？");

        Optional<ButtonType> result = alert.showAndWait();
        if (result.isPresent() && result.get() == ButtonType.OK) {
            try {
                int rows = drugDao.delete(Math.toIntExact(drug.getId()));
                if(rows > 0) {
                    drugList.remove(drug);
                    log.info("药品已删除: {}", drug.getName());
                } else {
                    log.warn("删除操作影响0行记录");
                }
            } catch (Exception e) {
                log.error("删除药品失败", e);
                showAlert("删除失败: " + e.getMessage());
            }
        }
    }

    /**
     * 处理保存操作
     */
    @FXML
    private void handleSave() {
        log.info("用户尝试保存药品信息");

        if (isInputValid()) {
            Drug drug = buildDrugFromFields();
            boolean isNewDrug = currentDrug == null;

            try {
                if (isNewDrug) {
                    // 新增药品
                    drug.setCreateTime(LocalDate.now());
                    int rows = drugDao.insert(drug);

                    if(rows > 0) {
                        log.info("新增药品成功: {}", drug.getName());
                        refreshData(); // 刷新数据
                    }
                } else {
                    // 编辑现有药品
                    drug.setId(currentDrug.getId());
                    drug.setCreateTime(currentDrug.getCreateTime());
                    int rows = drugDao.update(drug);

                    if(rows > 0) {
                        log.info("更新药品成功: {}", drug.getName());
                        refreshData(); // 刷新数据
                    }
                }

                // 重置界面
                editForm.setVisible(false);
                clearFormFields();
                currentDrug = null;

            } catch (Exception e) {
                log.error("保存药品失败", e);
                showAlert("保存失败: " + e.getMessage());
            }
        }
    }

    /**
     * 构建药品对象
     */
    private Drug buildDrugFromFields() {
        return Drug.builder()
                .name(nameField.getText().trim())
                .specification(specificationField.getText().trim())
                .manufacturer(manufacturerField.getText().trim())
                .price(Double.parseDouble(priceField.getText().trim()))
                .stock(Integer.parseInt(stockField.getText().trim()))
                .build();
    }

    /**
     * 显示错误提醒
     */
    private void showAlert(String message) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("错误");
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }

    /**
     * 处理取消操作
     */
    @FXML
    private void handleCancel() {
        log.info("用户取消编辑");
        editForm.setVisible(false);
        clearFormFields();
    }

    /**
     * 清空表单字段
     */
    private void clearFormFields() {
        nameField.clear();
        specificationField.clear();
        manufacturerField.clear();
        priceField.clear();
        stockField.clear();
    }

    /**
     * 填充表单字段
     */
    private void populateFormFields(Drug drug) {
        nameField.setText(drug.getName());
        specificationField.setText(drug.getSpecification());
        manufacturerField.setText(drug.getManufacturer());
        priceField.setText(String.valueOf(drug.getPrice()));
        stockField.setText(String.valueOf(drug.getStock()));
    }

    /**
     * 验证表单输入
     */
    private boolean isInputValid() {
        StringBuilder errorMessage = new StringBuilder();

        validateField(nameField, "药品名称", null, errorMessage);
        validateField(specificationField, "规格", null, errorMessage);
        validateField(manufacturerField, "生产厂家", null, errorMessage);

        // 验证单价
        validateField(priceField, "单价", value -> {
            try {
                Double.parseDouble(value);
                return true;
            } catch (NumberFormatException e) {
                return false;
            }
        }, errorMessage);

        // 验证库存
        validateField(stockField, "库存", value -> {
            try {
                Integer.parseInt(value);
                return true;
            } catch (NumberFormatException e) {
                return false;
            }
        }, errorMessage);

        if (!errorMessage.isEmpty()) {
            showAlert(errorMessage.toString());
            return false;
        }

        return true;
    }

    /**
     * 验证字段的通用方法
     */
    private void validateField(TextField field, String fieldName,
                               TextValidation validator, StringBuilder errorMessage) {
        String text = field.getText() != null ? field.getText().trim() : "";

        if (text.isEmpty()) {
            errorMessage.append(fieldName).append("不能为空！\n");
        } else {
            if (validator != null && !validator.isValid(text)) {
                errorMessage.append(fieldName).append("格式不正确！\n");
            }
        }
    }

    /**
     * 文本验证接口
     */
    private interface TextValidation {
        boolean isValid(String text);
    }
}